// 引入 Mock
import Mock from "mockjs";

// 定义数据类型
let { data } = Mock.mock({
  // 20条数据
  "data|76": [
    {
      "id|+1": 1,
      name: "@cname",
      // 商品种类
      "huodongName|1": ["端午节", "中秋节", "重阳节"],
      // 商品Id
      "huodongLeixing|1": ["线上", "线下"],
      "huodongshijian|1577836800000-1665971630620": 1577836800000,
      //商品名称
      goodsName: "@ctitle(10)",
      //商品地址
      goodsAddress: "@county(true)",
      //商品等级评价★
      "goodsStar|1-5": "★",
      //商品图片
      goodsImg: "@Image('100x100','@color','小甜甜')",
      //商品售价
      "goodsSale|30-500": 30,
    },
  ],
});
// 输出结果随机生成的数据（node index.js）
// console.log(data);

Mock.mock("/api/list", "post", (option) => {
  const { currentPage, pageSize, value } = JSON.parse(option.body);
  // value就是页面搜索框的内容,可能有，也可能没有
  let result = [];
  let count = 0;
  // if (value) {
  //   result = data.filter((item) => item.name === value);
  //   count = 1;
  // } else {
  //   result = data.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  //   count = data.length;
  // }

  if (value) {
    const filterValue = data.filter((item) => item.huodongLeixing === value);
    result = filterValue.slice(
      (currentPage - 1) * pageSize,
      currentPage * pageSize
    );
    count = filterValue.length;
  } else {
    result = data.slice((currentPage - 1) * pageSize, currentPage * pageSize);
    count = data.length;
  }

  return {
    result: result,
    status: 0,
    total: count,
  };
});

// 删除
Mock.mock("/api/remove", "post", (option) => {
  const { id } = JSON.parse(option.body);
  console.log(id);
  data = data.filter((item) => item.id !== id);
  return {
    status: 0,
    msg: "删除成功",
  };
});

// 删除
Mock.mock("/api/add", "post", (option) => {
  const { state } = JSON.parse(option.body);
  // data是一个对象
  data = [...data, state];
  return {
    status: 0,
    msg: "新增成功",
  };
});

export default Mock;
